package net.hn.hnms.biz.plan.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import net.hn.hnms.biz.plan.domain.PlanSale;
import net.hn.hnms.biz.plan.mapper.PlanSaleMapper;
import net.hn.hnms.biz.plan.request.PlanSaleReq;
import net.hn.hnms.biz.plan.service.IPlanSaleService;
import net.hn.hnms.biz.plan.vo.PlanSaleVO;
import net.hn.hnms.sys.common.core.constant.Constants;
import net.hn.hnms.sys.common.core.domain.ResponsePage;
import net.hn.hnms.sys.common.core.exception.HuaNengException;
import net.hn.hnms.sys.common.mybatis.core.page.PageQuery;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @author ly
 * 销售计划服务层实现
 * @date 2022-09-22
 */

@Service
public class PlanSaleServiceImpl extends BaseService<PlanSale, PlanSaleVO> implements IPlanSaleService {

    private PlanSaleMapper planSaleMapper;

    public PlanSaleServiceImpl(PlanSaleMapper planSaleMapper) {
        this.planSaleMapper = planSaleMapper;
    }

    /**
     * @param planSale
     * @param pageQuery 查询回采计划列表
     */
    @Override
    public ResponsePage<PlanSaleVO> selectPageList(PlanSaleReq planSale, PageQuery pageQuery) {

        Page<PlanSale> page = planSaleMapper.selectPage(pageQuery.build(), buildQuery(planSale).orderByDesc(PlanSale::getPlanCode).orderByDesc(PlanSale::getCreateTime));
        List<PlanSaleVO> list = page.getRecords().stream().map(o -> convert(o, PlanSaleVO.class, o.getPlanType())).collect(Collectors.toList());
        return new ResponsePage<>(list, page.getTotal());
    }


    /**
     * 构造查询条件
     *
     * @param req
     * @return LambdaQueryWrapper<PlanDevelopment> 查询条件
     */
    private LambdaQueryWrapper<PlanSale> buildQuery(PlanSaleReq req) {
        LambdaQueryWrapper<PlanSale> lqw = new LambdaQueryWrapper<PlanSale>()
                .like(StrUtil.isNotBlank(req.getPlanCode()), PlanSale::getPlanCode, req.getPlanCode())
                .like(StrUtil.isNotBlank(req.getPlanName()), PlanSale::getPlanName, req.getPlanName())
                .eq(StrUtil.isNotBlank(req.getMineCode()), PlanSale::getMineCode, req.getMineCode())
                .eq(StrUtil.isNotBlank(req.getPlanType()), PlanSale::getPlanType, req.getPlanType())
                .eq(StrUtil.isNotBlank(req.getSalesDestination()), PlanSale::getSalesDestination, req.getSalesDestination())
                .eq(StrUtil.isNotBlank(req.getTypeCoal()), PlanSale::getTypeCoal, req.getTypeCoal())
                .eq(StrUtil.isNotBlank(req.getStatus()), PlanSale::getStatus, req.getStatus());
        return lqw;
    }

    /**
     * @param planSale 查询掘进计划列表
     */
    @Override
    public List<PlanSaleVO> selectList(PlanSaleReq planSale) {
        List<PlanSale> list = planSaleMapper.selectList(buildQuery(planSale));
        return list.stream().map(o -> convert(o, PlanSaleVO.class, o.getPlanType())).collect(Collectors.toList());
    }

    /**
     * @param planSale 新增回采计划
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int insert(PlanSaleReq planSale) {
        //自动生成 计划名称 计划编号
        PlanSale insertObj = new PlanSale();
        copyProperties(planSale, insertObj, planSale.getPlanType());
        insertObj.setPlanName(generatePlanName(planSale.getPlanType(), insertObj.getPlanStartDate()));
        if (planSale.getSalesDestination() == null) {
            insertObj.setPlanCode(generatePlanCode(planSale.getPlanType(), insertObj.getPlanStartDate()));
        }
        if (planSale.getSalesDestination() != null) {
            String s = "";
            if (planSale.getSalesDestination().equals("0")) {
                s = "内销";
            }
            if (planSale.getSalesDestination().equals("1")) {
                s = "外销公路";
            }
            if (planSale.getSalesDestination().equals("2")) {
                s = "外销铁路";
            }
            insertObj.setPlanCode(s + generatePlanCode(planSale.getPlanType(), insertObj.getPlanStartDate()));
        }
        insertObj.setStatus("0");
        insertObj.setSaleType(CollUtil.join(planSale.getSaleTypes(), ","));
        QueryWrapper<PlanSale> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("plan_code", insertObj.getPlanCode()).eq("type_coal",planSale.getTypeCoal());
        if (planSaleMapper.selectCount(queryWrapper) > 0) {
            throw new HuaNengException(Constants.FAIL, "已存在同一时段的计划");
        }
        return planSaleMapper.insert(insertObj);
    }

    /**
     * @param idList 批量删除
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteBatch(List<String> idList) {
        planSaleMapper.deleteBatchIds(idList);
    }

    /**
     * @param planSale 单个修改 按照主键修改信息
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateById(PlanSaleReq planSale) {
        if (StrUtil.isBlank(planSale.getSalePlanId())) {
            throw new HuaNengException(Constants.FAIL, "id不能为空");
        }
        PlanSale updateObj = new PlanSale();
        copyProperties(planSale, updateObj, planSale.getPlanType());
        updateObj.setPlanName(generatePlanName(planSale.getPlanType(), updateObj.getPlanStartDate()));
        if (planSale.getSalesDestination() == null) {
            updateObj.setPlanCode(generatePlanCode(planSale.getPlanType(), updateObj.getPlanStartDate()));
        }
        if (planSale.getSalesDestination() != null) {
            String s = "";
            if (planSale.getSalesDestination().equals("0")) {
                s = "内销  1外销公路 2外销铁路";
            }
            if (planSale.getSalesDestination().equals("1")) {
                s = "外销公路";
            }
            if (planSale.getSalesDestination().equals("2")) {
                s = "外销铁路";
            }
            updateObj.setPlanCode(s + generatePlanCode(planSale.getPlanType(), updateObj.getPlanStartDate()));
        }

        updateObj.setSaleType(CollUtil.join(planSale.getSaleTypes(), ","));
        QueryWrapper<PlanSale> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("plan_code", updateObj.getPlanCode());
        queryWrapper.ne("sale_plan_id", updateObj.getSalePlanId());
        if (planSaleMapper.selectCount(queryWrapper) > 0) {
            throw new HuaNengException(Constants.FAIL, "已存在同一时段的计划");
        }
        int updateCount = planSaleMapper.updateById(updateObj);
        if (updateCount == 0) {
            throw new HuaNengException(Constants.FAIL, "数据不存在");
        }

    }

    /**
     * @param id 按主键id查询详情
     */
    @Override
    public PlanSaleVO selectDetailById(String id) {
        PlanSale planSale = planSaleMapper.selectById(id);
        if (planSale == null) {
            throw new HuaNengException(Constants.FAIL, "数据不存在");
        }
        return convertWithUser(planSale, PlanSaleVO.class);
    }


    /**
     * 启用/禁用
     *
     * @param id     数据id
     * @param status status: 0:启用 1:禁用
     */
    public void changeStatus(String id, Integer status) {
        if (status == 1 || status == 0) {
            PlanSale planMining = planSaleMapper.selectById(id);
            if (planMining == null) {
                throw new HuaNengException(Constants.FAIL, "数据不存在");
            }
            planMining.setStatus(status + "");
            int res = planSaleMapper.updateById(planMining);
            if (res == 0) {
                throw new HuaNengException(Constants.FAIL, "数据不存在");
            }
            return;
        }
        throw new HuaNengException(Constants.FAIL, "传入的参数错误");
    }
}
